//
//  SceneEditController.m
//  YSSmartHome
//
//  Created by yanghao on 16/9/18.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "SceneEditController.h"
#import "MoreCell.h"
#import "SceneEditCell.h"
#import "ZTLinkageInfo.h"
#import "LinkageDeviceSelectController.h"
#import "ZTLinkageUtil.h"
#import "DeviceConditionController.h"
#import "DataManager.h"
#import "MGSwipeTableCell.h"
#import "SettingTimeController.h"

static  NSString *const moreCellReuseIdentifier = @"moreCellReuseIdentifier";
static  NSString *const cellReuseIdentifier = @"cellReuseIdentifier";
@interface SceneEditController ()
<
MGSwipeTableCellDelegate
>
@property (nonatomic, strong)NSMutableArray *conds;
@property (nonatomic, strong)NSMutableArray *actions;
@property (nonatomic, assign)BOOL moreActionsFlag;
@property (nonatomic, assign)BOOL moreCondsFlag;
@end

@implementation SceneEditController

#pragma mark - life cycle
- (void)dealloc
{
    debugLogInfo(@"SceneEditController dealloc");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (instancetype)init
{
    return [self initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubviews];
    self.moreCondsFlag = YES;
    self.moreActionsFlag = YES;
    if (self.linkage)
    {
        self.actions = self.linkage.actionInfos;
        self.conds = self.linkage.condInfos;
        self.navigationItem.title = self.linkage.name;
    }
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reload:) name:@"kZTAddLinkageInfoNotifKey" object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
#pragma mark - setup

- (void)initSubviews{
    self.view.backgroundColor = kBgColor;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.backgroundColor = kBgColor;
    [self.tableView registerClass:[MoreCell class ] forCellReuseIdentifier:moreCellReuseIdentifier];
    self.tableView.rowHeight = 55;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(sure)];
}

- (void)reload:(NSNotification *)notif
{
    NSArray *linkageInfos = notif.object;
    NSMutableArray * delArray = [NSMutableArray array];
    for (ZTLinkageInfo *linkageInfo in linkageInfos)
    {
        if (ZTLinkageTypeCondition == linkageInfo.linkageType)
        {
            for (XAILinkItemDes *linkItemDes in self.conds)
            {
                if (XAI_DATA_TYPE_BIN_DATE == linkItemDes.tlv.type )
                {
                    if (XAI_DATA_TYPE_BIN_DATE == linkageInfo.linkItemDes.tlv.type ) {
                        [delArray addObject:linkItemDes];
                    }
                }
                else if (linkItemDes.oprId == linkageInfo.linkItemDes.oprId && linkItemDes.luid == linkageInfo.device.luid )
                {
                    [delArray addObject:linkItemDes];
                }
            }
            [self.conds removeObjectsInArray:delArray];
            NSArray *linkItems = [linkageInfos valueForKey:@"linkItemDes"];
            [self.conds addObjectsFromArray:linkItems];
        }
        else if (linkageInfo.linkageType == ZTLinkageTypeAction)
        {
            NSArray *linkItems = [linkageInfos valueForKey:@"linkItemDes"];
            [self.actions addObjectsFromArray:linkItems];
        }
    }
    [self.tableView reloadData];
}
- (void)setLinkage:(ZTLinkage *)linkage {
    _linkage = linkage;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - event response
- (void)sure
{
    [ZTLinkageUtil modifLinkageConds:self.conds actions:self.actions status:ZTLinkageStatus_Active name:self.linkage.name formula:@"00" linkageNum:self.linkage.num];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)moreConds {
    LinkageDeviceSelectController *conditionVc  = [[LinkageDeviceSelectController alloc]init];
    conditionVc.linkageType = ZTLinkageTypeCondition;
    conditionVc.isEdit = YES;
    [self.navigationController pushViewController:conditionVc animated:YES];
}
- (void)moreActions {
    LinkageDeviceSelectController *conditionVc  = [[LinkageDeviceSelectController alloc]init];
    conditionVc.linkageType = ZTLinkageTypeAction;
    conditionVc.isEdit = YES;
    [self.navigationController pushViewController:conditionVc animated:YES];
}

#pragma mark - UITableviewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        if (self.conds.count > 3)
        {
            if (self.moreCondsFlag)
            {
                return 4;
            }
            else
            {
                return self.conds.count;
            }
        } else {
            return self.conds.count;
        }
    }
    else if (section == 1)
    {
        if (self.actions.count > 3)
        {
            if (self.moreActionsFlag)
            {
                return 4;
            }
            else
            {
                return self.actions.count;
            }
        }
        else
        {
            return self.actions.count;
        }
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0)
    {
        if (self.moreCondsFlag)
        {
            if (indexPath.row == 3)
            {
                MoreCell *cell = [tableView dequeueReusableCellWithIdentifier:moreCellReuseIdentifier forIndexPath:indexPath];
                cell.title = @"更多启动条件";
                return cell;
            }
        }
        SceneEditCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier];
        if (!cell)
        {
            cell = [[SceneEditCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellReuseIdentifier];
        }
        cell.linkItemDes = self.conds[indexPath.row];
        cell.rightButtons = [self createRightButtons:1];
        cell.delegate = self;
        return cell;
    }
    else if (indexPath.section == 1)
    {
        if (self.moreActionsFlag)
        {
            if (indexPath.row == 3)
            {
                MoreCell *cell = [tableView dequeueReusableCellWithIdentifier:moreCellReuseIdentifier forIndexPath:indexPath];
                cell.title = @"更多动作";
                return cell;
            }
        }
        SceneEditCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier];
        if (!cell)
        {
            cell = [[SceneEditCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellReuseIdentifier];
        }
        cell.linkItemDes = self.actions[indexPath.row];
        cell.rightButtons = [self createRightButtons:1];
        cell.delegate = self;
        return cell;
    }
    return nil;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.section)
    {
        id cell = [tableView cellForRowAtIndexPath:indexPath];
        if ([cell isKindOfClass:[MoreCell class]])
        {
            self.moreCondsFlag = NO;
            [tableView reloadData];
            return;
        }
        XAILinkItemDes *linkageItem = self.conds[indexPath.row];
        if (XAI_DATA_TYPE_BIN_DATE ==  linkageItem.tlv.type)
        {
            SettingTimeController *settingTimeVc = [[SettingTimeController alloc]init];
            settingTimeVc.linkageType = ZTLinkageTypeCondition;
            settingTimeVc.linkItemDes = linkageItem;
            settingTimeVc.isEdit = YES;
            [self.navigationController pushViewController:settingTimeVc animated:YES];
        }
        else
        {
            DeviceConditionController* deviceConditionVc = [[DeviceConditionController alloc]init];
            deviceConditionVc.linkageType = ZTLinkageTypeCondition;
            deviceConditionVc.linkItemDes = linkageItem;
            deviceConditionVc.isEdit = YES;
            [self.navigationController pushViewController:deviceConditionVc animated:YES];
        }

    }
    else if (1 == indexPath.section)
    {
        id cell = [tableView cellForRowAtIndexPath:indexPath];
        if ([cell isKindOfClass:[MoreCell class]])
        {
            self.moreActionsFlag = NO;
            [tableView reloadData];
            return;
        }
        DeviceConditionController *deviceConditionVc = [[DeviceConditionController alloc]init];
        deviceConditionVc.linkageType = ZTLinkageTypeAction;
        XAILinkItemDes *linkItemDes = self.actions[indexPath.row];
        deviceConditionVc.linkItemDes = linkItemDes;
        deviceConditionVc.isEdit = YES;
        [self.navigationController pushViewController:deviceConditionVc animated:YES];
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *title = nil;
    if (0 == section)
    {
        title = @"启动条件";
    }
    else if (1 == section )
    {
        title = @"相关动作";
    }
    return title;

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 65;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *sectionFootview = [[UIView alloc]init];
    sectionFootview.backgroundColor = [UIColor whiteColor];
    UIButton *addmoreBtn = [[UIButton alloc]init];
    [addmoreBtn setBackgroundImage:[UIImage imageNamed:@"scene_circular_bg"] forState:UIControlStateNormal];
    [addmoreBtn setImage:[UIImage imageNamed:@"scene_white_add"] forState:UIControlStateNormal];
    addmoreBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    if (section == 0) {
        [addmoreBtn setTitle:@"添加更多条件" forState:UIControlStateNormal];
        [addmoreBtn addTarget:self action:@selector(moreConds) forControlEvents:UIControlEventTouchUpInside];
    } else if (section == 1) {
         [addmoreBtn setTitle:@"添加更多动作" forState:UIControlStateNormal];
        [addmoreBtn addTarget:self action:@selector(moreActions) forControlEvents:UIControlEventTouchUpInside];
    }
    [sectionFootview addSubview:addmoreBtn];
    [addmoreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(sectionFootview).offset(30);
        make.trailing.equalTo(sectionFootview.trailing).offset(-30);
        make.top.equalTo(sectionFootview.top).offset(10);
        make.bottom.equalTo(sectionFootview).offset(-10);
    }];
    return sectionFootview;
}

#pragma mark - private method
-(NSArray *)createRightButtons:(int)number
{
    NSMutableArray * result = [NSMutableArray array];
    NSArray *colors = @[RGBColor(239, 75, 58),RGBColor(204, 204, 204)];
    NSArray *icons = @[[UIImage imageNamed:@"scene_bigdel"], [UIImage imageNamed:@"scene_bigedit"]];
    for (int i = 0; i < number; ++i)
    {
        __weak typeof(self) weakSelf = self;
        MGSwipeButton * button = [MGSwipeButton buttonWithTitle:@"" icon:[icons objectAtIndex:i] backgroundColor:[colors objectAtIndex:i]  padding:15 callback:^BOOL(MGSwipeTableCell * sender){
            __strong typeof(weakSelf)strongSelf = weakSelf;
            if (!strongSelf) {
                return nil;
            }
            NSLog(@"Convenience callback received (left).");
            NSIndexPath *indexpath = [strongSelf.tableView indexPathForCell:sender];
            if (indexpath.section == 1) {
                [strongSelf.actions removeObjectAtIndex:indexpath.row];
            } else if (indexpath.section == 0) {
                [strongSelf.conds removeObjectAtIndex:indexpath.row];
            }
            [ZTLinkageUtil modifLinkageConds:strongSelf.conds actions:strongSelf.actions status:ZTLinkageStatus_Active name:strongSelf.linkage.name formula:@"0" linkageNum:strongSelf.linkage.num];
            [strongSelf.tableView reloadData];
            return YES;
        }];
        [result addObject:button];
    }
    return result;
}
- (void)modefiLinkage  {
    [ZTLinkageUtil modifLinkageConds:self.conds actions:self.actions status:ZTLinkageStatus_Active name:self.linkage.name formula:@"0" linkageNum:self.linkage.num];
}
@end
